<template>
  <ContentDetailWrap :title="t('warehouse.add')">
    <template #header>
      <BaseButton @click="go(-1)">
        {{ t('common.back') }}
      </BaseButton>
      <BaseButton type="primary" :loading="loading" @click="submit(formRef)">
        {{ t('action.save') }}
      </BaseButton>
    </template>
    <!--    表单-->
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="130px">
      <el-form-item :label="t('dealerAssetManagement.customer')" prop="customer_id">
        <el-input v-model="form.customer_name" clearable disabled style="width: 250px" />
        <el-button class="m-l-20px" size="small" type="primary" @click="handleOpenCustomer"
          >{{ t('dealerAssetManagement.select') }}
        </el-button>
      </el-form-item>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] m-t-40px m-b-20px"></div>

      <el-form-item :label="t('orderReturn.order_id')" prop="order_id">
        <el-input v-model="form.order_no" clearable disabled style="width: 250px" />
        <el-button class="m-l-20px" size="small" type="primary" @click="handleOpenOrder"
          >{{ t('orderReturn.selectOrders') }}
        </el-button>
      </el-form-item>
      <!-- 选择商品列表 -->
      <el-table
        :data="tableList"
        highlight-current-row
        row-key="id"
        stripe
        border
        show-summary
        :summary-method="getSummaries as any"
        :cell-style="{ textAlign: 'center' }"
        :header-cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :reserve-selection="true" width="55" />
        <el-table-column
          :label="t('orderReturn.index')"
          prop="id"
          min-width="100"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('orderReturn.product_name')"
          prop="product_name"
          min-width="200"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('orderReturn.warehouses_name')"
          min-width="200"
          prop="warehouses_name"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          :label="t('orderReturn.original_price')"
          min-width="200"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.original_price }}({{
              useEnumeratePicker(optionSet.currency, row.transaction_currency_id)
            }})
          </template>
        </el-table-column>
        <el-table-column
          :label="t('orderReturn.actual_price')"
          min-width="200"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            {{ row.price_selected_currency }}({{
              useEnumeratePicker(optionSet.currency, form.currency)
            }})
          </template>
        </el-table-column>
        <el-table-column
          :label="t('orderReturn.quantity')"
          min-width="180"
          :show-overflow-tooltip="true"
        >
          <template #default="{ row }">
            <el-input-number
              @change="handleChangeReturnNum"
              v-model="row!.return_quantity"
              :min="1"
              :max="row!.quantity ? parseInt(row!.quantity as string) : 100000"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--      分割线-->
      <div class="h-1px w-full bg-[#c8c9cc] my-10px"></div>
      <el-form-item :label="t('orderReturn.returnorder_type')" prop="returnorder_type">
        <el-select
          v-model="form.returnorder_type"
          :filterable="true"
          :placeholder="t('orderReturn.returnorder_type')"
          :clearable="false"
        >
          <el-option
            v-for="item in returnTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('orderReturn.total_amount')" prop="total_amount">
        <el-input
          v-model="form.total_amount"
          type="number"
          clearable
          :placeholder="t('orderReturn.total_amount')"
        />
      </el-form-item>
      <el-form-item :label="t('orderReturn.return_reason')" prop="return_reason">
        <el-select
          v-model="form.return_reason"
          :filterable="true"
          :placeholder="t('orderReturn.return_reason')"
          :clearable="false"
        >
          <el-option
            v-for="item in reasonList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('orderReturn.signatory')" prop="signatory">
        <el-select
          v-model="form.signatory"
          :filterable="true"
          :placeholder="t('orderReturn.signatory')"
          :clearable="false"
        >
          <el-option
            v-for="item in operatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderReturn.signing_date')" prop="signing_date">
        <el-date-picker
          v-model="form.signing_date"
          type="date"
          placeholder="签订时间"
          format="YYYY/MM/DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item :label="t('orderReturn.owner')" prop="owner">
        <el-select
          v-model="form.owner"
          :filterable="true"
          :placeholder="t('orderReturn.owner')"
          :clearable="false"
        >
          <el-option
            v-for="item in operatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('orderReturn.partner')" prop="partner">
        <el-select
          v-model="form.partner"
          :filterable="true"
          :placeholder="t('orderReturn.partner')"
          :clearable="false"
          multiple
        >
          <el-option
            v-for="item in operatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="t('orderReturn.remark')" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :autosize="{ minRows: 10, maxRows: 15 }"
          :placeholder="t('orderReturn.remark')"
        />
      </el-form-item>
    </el-form>
  </ContentDetailWrap>
  <DialogCustomerChecked
    ref="DialogCustomerCheckedRef"
    @expose-multiple-data="getExposeCustomerData"
  />
  <DialogOrderChecked ref="DialogOrderCheckedRef" @expose-multiple-data="getExposeOrderData" />
</template>

<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { ElButton, ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { createDataApi, getEnumApi, getOrderListApi } from '@/api/orderReturn'
import { getOrderEnumApi } from '@/api/order'
import DialogCustomerChecked from '@/views/Order/OrderReturn/components/DialogCustomerChecked/index.vue'
import DialogOrderChecked from '@/views/Order/OrderReturn/components/DialogOrderChecked/index.vue'
import { useUserStore } from '@/store/modules/user'
import Decimal from 'decimal.js'
import { useEnumeratePicker } from '@/utils'

const { t } = useI18n()
const { push, go } = useRouter()
const { query } = useRoute()
const userStore = useUserStore()

const loading = ref<boolean>(false)

const returnTypeList = ref<Array<Record<string, any>>>([])
const operatorList = ref<Array<Record<string, any>>>([])
const reasonList = ref<Array<Record<string, any>>>([])

const DialogCustomerCheckedRef = ref()
const DialogOrderCheckedRef = ref()

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({
  returnorder_type: '',
  customer_id: '',
  order_type: '',
  order_id: '',
  signatory: '',
  signing_date: '',
  owner: '',
  partner: '',
  product: [],
  total_amount: '',
  currency: ''
})

const multipleSelection = ref<any[]>([])
const selectionPak = ref<any[]>([])
const tableList = ref<Array<Record<string, any>>>([])
const rules = ref<FormRules>({
  customer_id: [
    {
      required: true,
      message: t('orderReturn.customerMsg'),
      trigger: 'change'
    }
  ],
  order_type: [
    {
      required: true,
      message: t('orderReturn.orderTypeMsg'),
      trigger: 'change'
    }
  ],
  order_id: [
    {
      required: true,
      message: t('orderReturn.orderMsg'),
      trigger: 'change'
    }
  ],
  returnorder_type: [
    {
      required: true,
      message: t('orderReturn.returnTypeMsg'),
      trigger: 'change'
    }
  ],
  signatory: [
    {
      required: true,
      message: t('orderReturn.signatoryMsg'),
      trigger: 'change'
    }
  ],
  signing_date: [
    {
      required: true,
      message: t('orderReturn.signingDateMsg'),
      trigger: 'change'
    }
  ],
  return_reason: [
    {
      required: true,
      message: t('orderReturn.returnReasonMsg'),
      trigger: 'change'
    }
  ],
  owner: [
    {
      required: true,
      message: t('orderReturn.ownerMsg'),
      trigger: 'change'
    }
  ],
  total_amount: [
    {
      required: true,
      message: t('orderReturn.totalAmountMsg'),
      trigger: 'change'
    }
  ]
})
//批量勾选
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  handleChangeReturnNum()
}

//接收勾选中的客户
const getExposeCustomerData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.customer_id = val[0].id
  form.value.owner = val[0].owner_id
  form.value.partner = val[0].partner
  form.value.customer_name = val[0].cusname
  form.value.order_id = ''
  form.value.order_no = ''
  tableList.value = []
}

const getExposeOrderData = (val: any[]) => {
  if (!val || !val.length) return
  form.value.order_id = val[0].id
  form.value.order_no = val[0].order_no
  form.value.order_type = val[0].order_type
  form.value.currency = val[0].currency
  tableList.value = val[0].item
}

const handleOpenOrder = () => {
  // 判断客户id不能为空
  if (!form.value.customer_id) {
    ElMessage.warning(t('orderReturn.customerIdMsg'))
    return
  }
  nextTick(() => {
    DialogOrderCheckedRef!.value!.dialogVisible = true
    DialogOrderCheckedRef!.value!.initialize(
      form.value.order_id ? [{ ...form.value, id: form.value.order_id }] : [],
      form.value.customer_id
    )
  })
}

const handleChangeReturnNum = () => {
  let cal_sum = 0
  if (multipleSelection.value.length) {
    multipleSelection.value.forEach((item: Record<string, any>) => {
      cal_sum += parseFloat(item.return_quantity) * parseFloat(item.price_selected_currency)
    })
    form.value.total_amount = cal_sum.toFixed(2)
  }
}

const handleOpenCustomer = () => {
  nextTick(() => {
    DialogCustomerCheckedRef!.value!.dialogVisible = true
    DialogCustomerCheckedRef!.value!.initialize(
      form.value.user_id ? [{ ...form.value, id: form.value.user_id }] : []
    )
  })
}

//列表合计
const getSummaries = (param: Record<string, any>) => {
  const { columns, data } = param
  const sums: (string | VNode)[] = []
  const columnList: number[] = [4, 5]
  columns.forEach((column: Record<string, any>, index: number) => {
    if (index === 0) {
      sums[index] = h('div', { style: { textDecoration: 'underline', textAlign: 'center' } }, [
        '合计'
      ])
      return
    }
    // if (columnList.includes(index)) {
    //   sums[index] = h('div', { style: { textAlign: 'center' } }, [])
    //   return
    // }
    if (index === 4) {
      const values = data.flatMap((item: Record<string, any>) => [item['original_price']])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)}`
      ])
    }
    if (index === 5) {
      const values = data.flatMap((item: Record<string, any>) => [item['price_selected_currency']])
      sums[index] = h('div', { style: { textAlign: 'center' } }, [
        `${values.reduce((prev: string, curr: string) => {
          return new Decimal(prev ? parseFloat(prev) : 0).add(
            new Decimal(curr ? parseFloat(curr) : 0)
          )
        }, 0)}`
      ])
    }
  })
  return sums
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      if (!multipleSelection.value.length) return ElMessage.warning('请勾选商品')

      const merge = selectionPak.value.concat(multipleSelection.value)
      // 使用 forEach 方法遍历合并后的数组
      form.value.product = []
      merge.forEach((item: any) => {
        // 将每个对象转换为所需的格式
        const formattedItem = {
          id: item.id, // 假设 item 对象中有 id 字段
          return_quantity: item.return_quantity || 2 // 假设默认退货数量为2，或者根据实际情况调整
        }
        form.value.product.push(formattedItem)
      })

      const resp = await createDataApi(form.value)
      if (resp.code === 0) {
        ElMessage.success(t('orderReturn.createSucMsg'))
        push({ path: '/order/orderReturn' })
      } else {
        ElMessage.error(resp.message as string)
      }
    }
  })
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getEnumApi({ field: 'all' })
  returnTypeList.value = resp.data.returnorder_type
  operatorList.value = resp.data.operator
  reasonList.value = resp.data.return_reason
}
//获取枚举
const optionSet = ref<Record<string, any>>({})
const getDropDownBoxOrderInfo = async () => {
  const resp = await getOrderEnumApi({ field: 'all' })
  optionSet.value = resp.data
}
const routerParams = ref<Record<string, any>>({})
const initData = () => {
  if (!query.data) return false
  routerParams.value = JSON.parse(decodeURIComponent(query.data as unknown as string)) || {}
  console.log('query', routerParams.value)
  // 客户设置默认值
  form.value.customer_id = routerParams.value.user_id
  form.value.owner = routerParams.value.owner
  form.value.partner = routerParams.value.partner ? routerParams.value.partner.split(',') : []
  form.value.customer_name = routerParams.value.user_name
  // 关联订单设置默认值
  getOrderInfo()
}
//初始化请求
const getOrderInfo = async () => {
  const params = {
    order_no: routerParams.value.order_no,
    order_type: routerParams.value.isWholesal ? 'wholesale' : 'order',
    pageIndex: 1,
    pageSize: 5
    // customer_id: form.value.customer_id
  }
  const resp = await getOrderListApi(params)
  if (resp?.data?.list && resp.data.list.length) {
    let val = resp.data.list
    form.value.order_id = val[0].id
    form.value.order_no = routerParams.value.order_no
    form.value.order_type = val[0].order_type
    tableList.value = val[0].item
  }
}
onMounted(() => {
  getDropDownBoxInfo()
  getDropDownBoxOrderInfo()
  initData()
})
</script>
<style lang="less" scoped></style>
